package com.example.backend.controller;

import com.example.backend.service.FunctionService;
import com.example.backend.util.PageUtils;
import com.example.backend.util.Result;
import com.example.backend.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Jcy
 * @Date 2022/5/6
 */
@RestController
@RequestMapping("/v1/admin/functions")
public class FunctionController {
    @Autowired
    private FunctionService functionService;
     @GetMapping
     public  Result getFunctions(int page, int pageSize){
        Map<String, Object> map = new HashMap<>();
         if(functionService.getFunctions(page, pageSize) != null){
        PageUtils p = functionService.getFunctions(page, pageSize);
        map.put("page", page);
        map.put("pageSize", pageSize);
        map.put("totalPageNum", p.getTotalPage());
        map.put("list", p.getList());
        return ResultGenerator.genSuccessResult("查看所有功能成功", map);
    }
    else{
        return ResultGenerator.genFailResult("查看所有功能失败", null);
            }
         }
         @PutMapping("/{functionId}")
         public Result addReduce(@PathVariable("functionId") int functionId){
         if(functionService.addReduce(functionId)==0){
             return ResultGenerator.genSuccessResult("增加/删除功能成功",null);
         }
            else if(functionService.addReduce(functionId)==1){
                 return ResultGenerator.genFailResult("功能不存在",null);
             }
         else {
             return ResultGenerator.genFailResult("增加/移除功能失败",null);
         }
     }
     @PutMapping("/{functionId}/name")
    public Result modifyFunction(@PathVariable("functionId") int functionId,@RequestBody Map<String, Object> params){
         if(functionService.modifyFunction(functionId,(String) params.get("functionName"))==0){
             return ResultGenerator.genSuccessResult("修改功能名称成功",null);
         }
         else{
             return ResultGenerator.genFailResult("修改功能名称失败",null);
         }
     }
}
